<script lang="ts" setup>
import { reactive, ref } from "vue"
import { useRouter } from "vue-router"
import { User, Lock, Key, Iphone, Link } from "@element-plus/icons-vue"
import ThemeSwitch from "@/components/ThemeSwitch/index.vue"
import { type FormInstance, FormRules, ElMessage } from "element-plus"
import { createRegDataApi, getPhoneCode } from "@/api/register"
import { checkPw, checkInvite } from "@/utils/validate"
const router = useRouter()
const loginFormRef = ref<FormInstance | null>(null)
const tid = router.currentRoute.value.query.tid || ""
/** 注册按钮 Loading */
const loading = ref(false)
const btnFlag = ref(false)
const send = ref("获取验证码")
const codeTime = ref(false)
/** 注册表单数据 */
const loginForm = reactive<any>({
  username: "",
  password: "",
  user_password1: "",
  phone: "",
  code: "",
  uuid: "",
  invite: tid
})

/** 登录表单校验规则 */

const checkPwTwo = (rule: any, value: any, callback: any) => {
  if (!value) {
    return callback(new Error("请输入密码！"))
  }
  setTimeout(() => {
    if (value !== loginForm.password) {
      callback(new Error("两次密码不一致！"))
    } else {
      callback()
    }
  }, 100)
}
const checkPhoneNumber = (rule: any, value: any, callback: any) => {
  const reg = /^1(3\d|4[5-9]|5[0-35-9]|6[567]|7[0-8]|8\d|9[0-35-9])\d{8}$/
  if (!value) {
    btnFlag.value = false
    return callback(new Error("请输入手机号！"))
  }
  setTimeout(() => {
    if (!reg.test(value)) {
      btnFlag.value = false
      callback(new Error("手机号格式错误！"))
    } else {
      callback()
      btnFlag.value = true
    }
  }, 100)
}
const loginFormRules: FormRules = {
  username: [{ required: true, message: "请输入用户名", trigger: "blur" }],
  phone: [{ required: true, validator: checkPhoneNumber, trigger: "blur" }],
  password: [{ required: true, validator: checkPw, trigger: "blur" }],
  invite: [{ required: true, validator: checkInvite, trigger: "blur" }],
  user_password1: [{ required: true, validator: checkPwTwo, trigger: "blur" }]
}

/** 注册逻辑 */
const handleLogin = () => {
  loginFormRef.value?.validate((valid: boolean) => {
    if (valid) {
      loading.value = true
      createRegDataApi(loginForm)
        .then((res: any) => {
          if (res.code == 200) {
            ElMessage.success("注册成功,即将跳转登录页！")
            setTimeout(() => {
              router.push({ path: "/login" })
            }, 1000)
          }
        })
        .finally(() => {
          loading.value = false
        })
    } else {
      return false
    }
  })
}
/**获取手机验证码 */
const time = ref(60)
const getCode = () => {
  const reg = /^1(3\d|4[5-9]|5[0-35-9]|6[567]|7[0-8]|8\d|9[0-35-9])\d{8}$/
  loginForm.uuid = new Date().getTime() + ""
  if (loginForm.phone && reg.test(loginForm.phone)) {
    codeTime.value = true
    const timer = setInterval(() => {
      time.value--
      if (time.value >= 0) {
        send.value = time.value + "s后刷新"
      } else if (time.value < 0) {
        send.value = "获取验证码"
        codeTime.value = false
        clearInterval(timer)
        time.value = 60
      }
    }, 1000)
    getPhoneCode({ mobile: loginForm.phone, uuid: loginForm.uuid }).then((res) => {
      console.log(res)
    })
  } else {
    ElMessage.warning("请输入正确的手机号！")
  }
}
</script>

<template>
  <div class="login-container">
    <ThemeSwitch class="theme-switch" />
    <div class="login-card">
      <div class="title">
        <img src="@/assets/layout/logo-text-2.png" />
      </div>
      <div class="content">
        <el-form ref="loginFormRef" :model="loginForm" :rules="loginFormRules" @keyup.enter="handleLogin">
          <el-form-item prop="username">
            <el-input v-model.trim="loginForm.username" placeholder="用户名" type="text" tabindex="1" :prefix-icon="User"
              size="large" />
          </el-form-item>
          <el-form-item prop="password">
            <el-input v-model.trim="loginForm.password" placeholder="密码" type="password" tabindex="2"
              :prefix-icon="Lock" size="large" show-password />
          </el-form-item>
          <el-form-item prop="user_password1">
            <el-input v-model.trim="loginForm.user_password1" placeholder="确认密码" type="password" tabindex="2"
              :prefix-icon="Lock" size="large" show-password />
          </el-form-item>
          <el-form-item prop="phone">
            <el-input v-model.trim="loginForm.phone" placeholder="手机号" type="text" tabindex="2" :prefix-icon="Iphone"
              size="large" style="width: 260px" />
            <el-button type="primary" size="large" style="margin-left: 10px" :disabled="codeTime" @click="getCode">
              {{ send }}
            </el-button>
          </el-form-item>
          <el-form-item prop="code">
            <el-input v-model.trim="loginForm.code" placeholder="验证码" type="text" tabindex="3" maxlength="7"
              :prefix-icon="Key" size="large" />
          </el-form-item>
          <el-form-item prop="invite">
            <el-input v-model.trim="loginForm.invite" placeholder="邀请码" type="text" tabindex="1" :prefix-icon="Link"
              size="large" :disabled="tid !== ''" />
          </el-form-item>
          <router-link class="link-to-reg" to="/login">已有账号?前往登录</router-link>
          <el-button class="btn" :loading="loading" type="primary" size="large" @click.prevent="handleLogin">
            注 册
          </el-button>
        </el-form>
      </div>
    </div>
    <div class="footer">
      <!-- <el-link href="https://beian.miit.gov.cn/">豫ICP备2021038539号-2</el-link> -->
    </div>
  </div>
</template>

<style lang="scss" scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  min-height: 100%;

  .footer {
    position: fixed;
    bottom: 10px;
    padding: 20px;
    line-height: 30px;
    text-align: center;
  }

  .theme-switch {
    position: fixed;
    top: 5%;
    right: 5%;
    cursor: pointer;
  }

  .login-card {
    width: 480px;
    border-radius: 20px;
    box-shadow: 0 0 10px #dcdfe6;
    background-color: #fff;
    overflow: hidden;

    .title {
      display: flex;
      justify-content: center;
      align-items: center;
      height: 150px;

      img {
        height: 100%;
      }
    }

    .content {
      padding: 20px 50px 50px 50px;

      :deep(.el-input-group__append) {
        padding: 0;
        overflow: hidden;

        .el-image {
          width: 100px;
          height: 40px;
          border-left: 0px;
          user-select: none;
          cursor: pointer;
          text-align: center;
        }
      }

      ::v-deep(.el-form-item__content) {
        .el-button {
          padding: 18px;
        }
      }

      .btn {
        width: 100%;
        margin-top: 10px;
      }
    }
  }
}

.link-to-reg {
  display: block;
  text-align: center;
  font-size: 12px;
  color: #409eff;
}
</style>
